C# OOP Concepts: Class, Object, Inheritance, Polymorphism Examples
๐ฏ 1. Class & Object
Basic Definition:
A class is a blueprint or template that defines what an object will be. An object is an actual instance created from that class.
// CLASS (Blueprint) class Car { public string color; public string model; public void Honk() { Console.WriteLine("Beep beep!"); } } // OBJECTS (Actual instances) Car myCar = new Car(); myCar.color = "Red"; myCar.model = "Toyota"; myCar.Honk(); Car yourCar = new Car(); yourCar.color = "Blue"; yourCar.model = "Honda"; yourCar.Honk();
Explanation:
Class is like a cookie cutter - it defines the shape
Objects are the actual cookies made from that cutter
You can create multiple objects from one class, each with different data
๐ 2. Encapsulation
Basic Definition:
Encapsulation means bundling data and methods together, and restricting direct access to some components to protect data integrity.
class BankAccount { // Private field - hidden from outside private double balance = 0; // Public method - controlled access public void Deposit(double amount) { if(amount > 0) { balance += amount; Console.WriteLine($"Deposited: ${amount}"); } else { Console.WriteLine("Invalid amount!"); } } public void Withdraw(double amount) { if(amount > 0 && amount <= balance) { balance -= amount; Console.WriteLine($"Withdrawn: ${amount}"); } else { Console.WriteLine("Insufficient funds!"); } } public double GetBalance() { return balance; } } // Usage BankAccount account = new BankAccount(); account.Deposit(1000); // ✅ Allowed - through method account.Withdraw(200); // ✅ Allowed - through method Console.WriteLine(account.GetBalance()); // ✅ Allowed - through method // account.balance = 5000; // ❌ NOT allowed - direct access prevented // account.balance = -100; // ❌ NOT allowed - prevents invalid data
Explanation:
Private fields (
balance) are hidden like money in a safePublic methods are like bank tellers - they control access
Prevents invalid operations (negative deposits, over-withdrawals)
The internal implementation can change without affecting users
๐จ๐ฆ 3. Inheritance
Basic Definition:
Inheritance allows a new class to acquire properties and behaviors of an existing class, promoting code reuse.
// PARENT CLASS (Base class) class Animal { public string Name; public void Eat() { Console.WriteLine($"{Name} is eating..."); } public void Sleep() { Console.WriteLine($"{Name} is sleeping..."); } } // CHILD CLASSES (Derived classes) - Inherit from Animal class Dog : Animal // Dog inherits from Animal { public void Bark() { Console.WriteLine($"{Name} says: Woof woof!"); } } class Cat : Animal // Cat inherits from Animal { public void Meow() { Console.WriteLine($"{Name} says: Meow!"); } } // Usage Dog myDog = new Dog(); myDog.Name = "Buddy"; myDog.Eat(); // Inherited from Animal myDog.Sleep(); // Inherited from Animal myDog.Bark(); // Its own method Cat myCat = new Cat(); myCat.Name = "Whiskers"; myCat.Eat(); // Inherited from Animal myCat.Sleep(); // Inherited from Animal myCat.Meow(); // Its own method
Explanation:
Parent class contains common features (eat, sleep)
Child classes get all parent features automatically
Each child can add its own special features (bark, meow)
Avoids code duplication - write once, use everywhere
๐ญ 4. Polymorphism
Basic Definition:
Polymorphism means "many forms" - the same method or property can behave differently in different classes.
class Shape { public virtual void Draw() // Virtual = can be overridden { Console.WriteLine("Drawing a shape"); } } class Circle : Shape { public override void Draw() // Override = provide new behavior { Console.WriteLine("Drawing a circle ⭕"); } } class Square : Shape { public override void Draw() // Override = provide new behavior { Console.WriteLine("Drawing a square ◼️"); } } class Triangle : Shape { public override void Draw() // Override = provide new behavior { Console.WriteLine("Drawing a triangle ๐บ"); } } // Usage Shape[] shapes = new Shape[3]; // Array of base type shapes[0] = new Circle(); // But holds different types shapes[1] = new Square(); shapes[2] = new Triangle(); foreach (Shape shape in shapes) { shape.Draw(); // Same method, different behaviors! } // Output: // Drawing a circle ⭕ // Drawing a square ◼️ // Drawing a triangle ๐บ
Explanation:
Same method name (
Draw) but different implementationsVirtual in parent = "child classes can change this"
Override in child = "I'm providing my own version"
Useful when you want to treat different objects the same way
๐ 5. Abstraction
Basic Definition:
Abstraction means showing only essential features and hiding the complex implementation details.
// Abstract class - cannot create objects directly abstract class Vehicle { public string Model { get; set; } // Abstract method - no implementation, must be overridden public abstract void Start(); // Concrete method - has implementation public void Stop() { Console.WriteLine($"{Model} has stopped"); } } class Car : Vehicle { public override void Start() // Must implement abstract method { Console.WriteLine($"{Model} car: Turn key to start"); } } class Bike : Vehicle { public override void Start() // Must implement abstract method { Console.WriteLine($"{Model} bike: Kick start"); } } // Usage Vehicle myCar = new Car { Model = "Toyota" }; Vehicle myBike = new Bike { Model = "Yamaha" }; myCar.Start(); // "Toyota car: Turn key to start" myCar.Stop(); // "Toyota has stopped" myBike.Start(); // "Yamaha bike: Kick start" myBike.Stop(); // "Yamaha has stopped" // Vehicle v = new Vehicle(); // ❌ ERROR - cannot create abstract class
Explanation:
Abstract class = incomplete blueprint, cannot create objects
Abstract methods = "must do this" without saying how
Concrete methods = "already done, you can use as-is"
Forces child classes to provide their own implementations
๐ 6. Interface
Basic Definition:
An interface defines a contract that classes must follow - it specifies what methods/properties must be implemented, but not how.
// INTERFACES (Contracts) interface IFlyable { void Fly(); // No implementation, just signature } interface ISwimmable { void Swim(); } // CLASSES implementing interfaces class Bird : IFlyable { public void Fly() // Must implement Fly() method { Console.WriteLine("Bird is flying by flapping wings ๐️"); } } class Airplane : IFlyable { public void Fly() // Must implement Fly() method { Console.WriteLine("Airplane is flying using jet engines ✈️"); } } class Duck : IFlyable, ISwimmable // Can implement multiple interfaces { public void Fly() { Console.WriteLine("Duck is flying short distances ๐ฆ"); } public void Swim() { Console.WriteLine("Duck is swimming in water ๐"); } } // Usage IFlyable[] flyingThings = new IFlyable[3]; flyingThings[0] = new Bird(); flyingThings[1] = new Airplane(); flyingThings[2] = new Duck(); foreach (IFlyable item in flyingThings) { item.Fly(); // All can fly, but differently }
Explanation:
Interface = contract saying "you must have these methods"
No implementation in interface, only method signatures
Classes promise to implement all interface methods
Multiple interfaces allowed (unlike single inheritance)
Enables different classes to be used interchangeably
๐ฏ Key Differences Summary:
| Concept | Simple Meaning | Real-world Example |
|---|---|---|
| Class & Object | Blueprint vs Actual thing | Cookie cutter vs Cookies |
| Encapsulation | Data protection | ATM machine controlling cash access |
| Inheritance | Parent-child relationship | Family traits passed down |
| Polymorphism | Same action, different results | Power button (TV vs Computer) |
| Abstraction | Hide complexity | Car dashboard hiding engine |
| Interface | Contract or capability | "Can fly" contract for birds/planes |
Comments
Post a Comment